package Controlor;

import Model.DAO.uselessDao.BookDao;
import Model.useless.BookForm;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/insertnewbook")
public class CheckInsertbook extends HttpServlet{

    private boolean isIntNum(String str){
        for (int i = 0; i < str.length(); i++){
            if (!Character.isDigit(str.charAt(i)))
                return false;
      }
      return true;
    }
    private boolean isDoubleNum(String str){
        //正则表达式
            String reg = "^[0-9]+(.[0-9]+)?$";
            return str.matches(reg);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        BookForm bookForm = new BookForm();
        boolean rst = false;
        String bn = req.getParameter("bookname");
        String pg = req.getParameter("page");
        String ti = req.getParameter("typeid");
        String pr = req.getParameter("price");
        String au = req.getParameter("author");
        String IS = req.getParameter("ISBN");
        boolean flag = isIntNum(pg)&&isIntNum(ti)&&isDoubleNum(pr);
        if(flag) {
            bookForm.setAuthor(au);
            bookForm.setBookname(bn);
            bookForm.setId(new BookDao().getCount()+1);
            //System.out.println(bookForm.getId()+"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            bookForm.setIddelete(0);
            bookForm.setISBN(IS);
            bookForm.setPage(Integer.parseInt(pg));
            bookForm.setTypeid(Integer.parseInt(ti));
            bookForm.setPrice(Double.parseDouble(pr));
            rst = new BookDao().insertBook(bookForm);
        }
        if(rst){
            //转到系统主界面
            req.setAttribute("insertinfo",1);
            req.getRequestDispatcher("Tip.jsp").forward(req, resp);
        }
        else {
            req.setAttribute("insertinfo",0);
            req.getRequestDispatcher("Tip.jsp").forward(req, resp);//转到错误页
        }
    }
}

